import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:test01/okhttp_test/pojo/login_request_pojo.dart';
import 'package:test01/okhttp_test/util/request_http.dart';

import 'user_name_page.dart';


/*
*
*
* 登录界面----------获取用户头像以及昵称
*
*
* */



void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    ///禁止程序横屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp, //只能纵向
      DeviceOrientation.portraitDown, //只能纵向
    ]);

    return MaterialApp(
      home: UserNickName(),
    );
  }
}


class UserNickName extends StatefulWidget {
  const UserNickName({Key key}) : super(key: key);

  @override
  _UserNickNameState createState() => _UserNickNameState();
}

class _UserNickNameState extends State<UserNickName> {
  ///图片地址
  var picUrl;
  ///输入的昵称
  String names;

  String url="http://devpic.aimymusic.com/ifapp/1008744/EZdcnsvFG9wjKuYG0UP8rA==.png";
  ///焦点
  FocusNode _focusNode = FocusNode();

  ///是否获取焦点
  bool isFocusNode=false;

  ///从相册获取图片地址
  _openGallery() async {
    final pickedFile = await ImagePicker().getImage(source: ImageSource.gallery);
    final File image = File(pickedFile.path);
    setState(() {
      picUrl = image;
      print("-------------------获取的图片路径$picUrl----------------------");
    });
  }


  @override
  void initState() {
    super.initState();
    //输入框焦点
    _focusNode.addListener((){
      if (_focusNode.hasFocus) {
        isFocusNode=true;
        setState(() {
        });
        print("$isFocusNode");
      }
    });

  }

  @override
  void dispose() {
    _focusNode.unfocus();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: EdgeInsets.only(top: 128,left: 41),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              picUrl!=null?
              Container(
                width: 90,
                height: 90,
                child:  Stack(
                  children: <Widget>[
                    Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(60.0)),
                      ),
                      child:ClipRRect(
                        borderRadius: BorderRadius.circular(90.0),
                        child:  Image.file(picUrl,width: 90,height: 90,fit: BoxFit.cover,),
                        ),
                    ),
                    Container(
                      width: 24,
                      height: 24,
                      margin: EdgeInsets.only(left: 60,top: 66),
                      padding: EdgeInsets.all(5),
                      decoration: BoxDecoration(
                        color: Color.fromRGBO(17, 17, 17, 1),
                        border: Border.all(width: 1,color: Colors.white),
                        borderRadius: BorderRadius.all(Radius.circular(24.0)),
                      ),
                      child: Icon(Icons.add,color: Color.fromRGBO(255, 255, 255, 1),size:13.4,),
                    ),
                  ],
                ),
              ):
              GestureDetector(
                onTap: (){
                  _openGallery();
                },
                child: Container(
                  width: 90,
                  height: 90,
                  child:  Stack(
                    children: <Widget>[
                      Container(
                        width: 90,
                        height: 90,
                        decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.all(Radius.circular(60.0)),
                        ),
                      ),
                      Container(
                        width: 24,
                        height: 24,
                        margin: EdgeInsets.only(left: 60,top: 66),
                        padding: EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          color: Color.fromRGBO(17, 17, 17, 1),
                          border: Border.all(width: 1,color: Colors.white),
                          borderRadius: BorderRadius.all(Radius.circular(24.0)),
                        ),
                        child: Icon(Icons.add,color: Color.fromRGBO(255, 255, 255, 1),size:13.4,),
                      ),
                    ],
                  ),
                ),
              ),
        Container(
            margin:EdgeInsets.only(top: 48),
            height: 44,
            width: MediaQuery.of(context).size.width-82,
            child: TextField(
              ///焦点监听
              focusNode: _focusNode,
              ///设置光标颜色
              cursorColor: Color.fromRGBO(51, 51, 51, 1),
              decoration: InputDecoration(
                ///隐藏最大输入统计
                counterText: "",
                suffixIcon: Container(
                  width: 35,
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.only(bottom: 6,top: 6),
                  child:Text(isFocusNode?names!=null?"${names.length}/15":"0/15":"",style: TextStyle(fontSize: 14,color: Color.fromRGBO(196, 196, 196, 1)),),
                ),
                hintText: '戳这里输入昵称',
                hintStyle: TextStyle(color: Colors.grey),
                hintMaxLines: 1,

                /// 不是焦点的时候颜色
                enabledBorder: UnderlineInputBorder(
                  borderSide:
                  BorderSide(color: Color.fromRGBO(243, 243, 243, 1)),
                ),

                /// 焦点集中的时候颜色
                focusedBorder: new UnderlineInputBorder(
                  borderSide:
                  BorderSide(color: Color.fromRGBO(243, 243, 243, 1)),
                ),
              ),

              onChanged: (value){
                setState(() {
                  names = value;
                });
              },
              maxLength: 15,
              maxLines: 1,
            )
        ),
              GestureDetector(
                onTap: () async{
                  if(names!=null&&picUrl!=null){
                  bool xx= await perfectUserInfo(names,url,"/ucenter/web/user/perfectUserInfo");
                   if(xx){
                     ///获取最新的token
                     LoginRequst loginRequst=LoginRequst(authorization:"Basic dXNlckFwcDpBaW15Rml0bmVzcw==",grant_type:"refresh_token",refresh_token:refreshtokens);
                     LoginRespons loginRespons=await getinittokens(loginRequst, "/uaa/oauth/login");
                     if(loginRespons!=null){
                       Fluttertoast.showToast(msg:"登录成功！",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.BOTTOM,
                           textColor: Colors.white,
                           fontSize: 14.0
                       );
                       ///界面跳转
                       Navigator.push(context, MaterialPageRoute(builder: (context) => UserNamePage(nicknames:names,picurl:picUrl)),);
                       tokens="${loginRespons.token_type} ${loginRespons.access_token}";
                       refreshtokens="${loginRespons.refresh_token}";
                     }

                   }else{
                     Fluttertoast.showToast(msg: "登录失败",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.BOTTOM,
                         textColor: Colors.white,
                         fontSize: 16.0
                     );
                   }
                  }
                },
                child:names!=null&&picUrl!=null?
                Container(
                  width: MediaQuery.of(context).size.width-82,
                  height: 44,
                  margin: EdgeInsets.only(top: 32),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(17, 17, 17, 1),
                    borderRadius: BorderRadius.circular(3.0),
                  ),
                  child: Text("完成",style: TextStyle(fontSize: 16,color: Color.fromRGBO(255, 255, 255, 1)),),
                ):
                Container(
                  width: MediaQuery.of(context).size.width-82,
                  height: 44,
                  margin: EdgeInsets.only(top: 32),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(17, 17, 17, 0.06),
                    borderRadius: BorderRadius.circular(3.0),
                  ),
                  child: Text("完成",style: TextStyle(fontSize: 16,color: Color.fromRGBO(153, 153, 153, 1)),),
                ),


              ),
            ],
          ),
        ),
      ),
    );
  }
}


